import IComponentServer from "../IComponentServer";

import { TUIChatStoreType } from "../types";

import store from "../../store";

import httpInterceptor from '@/utils/http.interceptor.js';
import { stringify } from "aegis-web-sdk/lib/packages/core/src";

import timStorage from "../../../utils/tim-storage.js";
import { JsxEmit } from "typescript";

/**
 * class TUIChatServer
 *
 * TUIChat 逻辑主体
 */
export default class TUIChatServer extends IComponentServer {
	public TUICore: any;
	public currentStore: any = {};
	public store = store.state.timStore;

	constructor(TUICore: any) {
		super();
		this.TUICore = (uni as any).$TUIKit;
		this.bindTIMEvent();
		this.updateStore();
	}

	/**
	 * 组件销毁
	 */
	public destroyed() {
		this.unbindTIMEvent();
	}

	/**
	 * 数据监听回调
	 *
	 * @param {any} newValue 新数据
	 * @param {any} oldValue 旧数据
	 *
	 */
	private updateStore() {
		// this.getMessageList({
		// 	conversationID: this.store.conversationID,
		// 	conversationType: this.store.conversation?.type,
		// 	count: 15,
		// });
		this.getLocalCacheMessageList({
			conversationID: this.store.conversationID,
			conversationType: this.store.conversation?.type,
			count: 15,
		});
		store.commit("timStore/resetChat");
	}

	/**
	 * /////////////////////////////////////////////////////////////////////////////////
	 * //
	 * //                                    TIM 事件监听注册接口
	 * //
	 * /////////////////////////////////////////////////////////////////////////////////
	 */

	private bindTIMEvent() {
		this.TUICore.on(
			uni.$TIM.EVENT.MESSAGE_RECEIVED,
			this.handleMessageReceived,
			this
		);
		this.TUICore.on(
			uni.$TIM.EVENT.MESSAGE_MODIFIED,
			this.handleMessageModified,
			this
		);
		this.TUICore.on(
			uni.$TIM.EVENT.MESSAGE_REVOKED,
			this.handleMessageRevoked,
			this
		);
		this.TUICore.on(
			uni.$TIM.EVENT.MESSAGE_READ_BY_PEER,
			this.handleMessageReadByPeer,
			this
		);
		this.TUICore.on(
			uni.$TIM.EVENT.GROUP_LIST_UPDATED,
			this.handleGroupListUpdated,
			this
		);
	}

	private unbindTIMEvent() {
		this.TUICore.off(
			uni.$TIM.EVENT.MESSAGE_RECEIVED,
			this.handleMessageReceived
		);
		this.TUICore.off(
			uni.$TIM.EVENT.MESSAGE_MODIFIED,
			this.handleMessageModified
		);
		this.TUICore.off(uni.$TIM.EVENT.MESSAGE_REVOKED, this.handleMessageRevoked);
		this.TUICore.off(
			uni.$TIM.EVENT.MESSAGE_READ_BY_PEER,
			this.handleMessageReadByPeer
		);
		this.TUICore.off(
			uni.$TIM.EVENT.GROUP_LIST_UPDATED,
			this.handleGroupListUpdated,
			this
		);
	}

	private handleMessageReceived(event: any) {
		event.data.forEach((item) => {
			if (item.conversationID === this.store.conversationID) {
				uni.$TUIKit.TUIConversationServer.setMessageRead(item.conversationID);
				
				const messageList = [...this.store.messageList, item];
				// 更新 messageList
				store.commit("timStore/setMessageList", messageList);
			}
		});
	}

	private handleMessageModified(event: any) {
		const middleData = this.store.messageList;
		this.store.messageList = [];
		this.store.messageList = middleData;
	}

	private handleMessageRevoked(event: any) {
		// const middleData = this.store.messageList;
		// this.store.messageList = [];
		// this.store.messageList = middleData;
	}

	private async handleMessageReadByPeer(event: any) {
		// sdk message 消息引用关系会自动更新
		const middleData = this.store.messageList;
		// 兼容小程序，在小程序中 setData 是异步
		await store.commit("timStore/resetChat");
		await store.commit("timStore/setMessageList", middleData);
	}

	private handleGroupListUpdated(event: any) {
		event?.data.map((item: any) => {
			if (item?.groupID === this?.store?.conversation?.groupProfile?.groupID) {
				this.store.conversation.groupProfile = item;
				const midden = this.store.conversation;
				this.store.conversation = {};
				this.store.conversation = midden;
			}
			return item;
		});
	}

	/**
	 * /////////////////////////////////////////////////////////////////////////////////
	 * //
	 * //                                 处理 TIM 接口参数及回调
	 * //
	 * /////////////////////////////////////////////////////////////////////////////////
	 */

	/**
	 * 创建消息生成参数
	 *
	 * @param {Object} content 消息体
	 * @param {String} type 消息类型 text: 文本类型 file: 文件类型 face: 表情 location: 地址 custom: 自定义 merger: 合并 forward: 转发
	 * @param {Callback} callback 回调函数
	 * @param {any} to 发送的对象
	 * @returns {options} 消息参数
	 */
	public handleMessageOptions(
		content: any,
		type: string,
		callback?: any,
		to?: any
	) {
		const options: any = {
			to: "",
			conversationType: to?.type || this.store.conversation.type,
			payload: content,
			needReadReceipt: true,
		};
		if (type === "file" && callback) {
			options.onProgress = callback;
		}
		switch (options.conversationType) {
			case uni.$TIM.TYPES.CONV_C2C:
				options.to =
					to?.userProfile?.userID ||
					this.store.conversation?.userProfile?.userID ||
					"";
				break;
			case uni.$TIM.TYPES.CONV_GROUP:
				options.to =
					to?.groupProfile?.groupID ||
					this.store.conversation?.groupProfile?.groupID ||
					"";
				break;
			default:
				break;
		}
		return options;
	}

	//合并转发处理发送函数
	public handleMessageOptions1(
		content: any,
		type: string,
		callback?: any,
		to?: any
	) {
		const options: any = {
			to: content.to,
			conversationType: content.conversationType,
			payload: content,
			needReadReceipt: true,
		};
		if (type === "file" && callback) {
			options.onProgress = callback;
		}
		return options;
	}

	/**
	 * 处理异步函数
	 *
	 * @param {callback} callback 回调函数
	 * @returns {Promise} 返回异步函数
	 */
	public handlePromiseCallback(callback: any) {
		return new Promise<void>((resolve, reject) => {
			const config = {
				TUIName: 'TUIChat',
				callback: () => {
					callback && callback(resolve, reject);
				},
			};
			this.TUICore.setAwaitFunc(config.TUIName, config.callback);
		});
	}

	/**
	 * 文件上传进度函数处理
	 *
	 * @param {number} progress 文件上传进度 1表示完成
	 * @param {message} message 文件消息
	 */
	public handleUploadProgress(progress: number, message: any) {
		this.store.messageList.map((item: any) => {
			if (item.ID === message.ID) {
				item.progress = progress;
			}
			return item;
		});
	}

	/**
	 * /////////////////////////////////////////////////////////////////////////////////
	 * //
	 * //                                 对外方法
	 * //
	 * /////////////////////////////////////////////////////////////////////////////////
	 */

	// /**
	//  * 发送文本消息
	//  *
	//  * @param {any} text 发送的消息
	//  * @returns {Promise}
	//  */
	/**
	 * 发送文本消息
	 *
	 * @param {any} text 发送的消息
	 * @returns {Promise}
	 */
	public sendTextMessage(text: any): Promise<any> {
		return new Promise<void>(async (resolve, reject) => {
			try {
				// console.log("text", text)
				const options = this.handleMessageOptions({ text }, "text");
				console.log("options", JSON.stringify(options))
				const message = this.TUICore.createTextMessage(options);
				// 优化写法
				const messageList = [...this.store.messageList, message];
				// console.log("__________________________________________________________________________", JSON.stringify(message))
				store.commit("timStore/setMessageList", messageList);
				const imResponse = await this.TUICore.sendMessage(message, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				this.store.messageList = this.store.messageList.map((item: any) => {
					if (item.ID === imResponse.data.message.ID) {
						return imResponse.data.message;
					}
					return item;
				});

				//保存到本地
				console.log("imResponse.code == 0", imResponse.code == 0)
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([message], false);
				}

				resolve(imResponse);
			} catch (error) {
				reject(error);
				const middleData = this.store.messageList;
				store.commit("timStore/resetChat");
				store.commit("timStore/setMessageList", middleData);
			}
		});
	}

	// /**
	//  * 发送@文本消息
	//  *
	//  * @param {any} text 发送的消息
	//  * @returns {Promise}
	//  */
	/**
	 * 发送文本消息
	 *
	 * @param {any} text 发送的消息
	 * @returns {Promise}
	 */
	public sendAtTextMessage(options: any): Promise<any> {
		return new Promise<void>(async (resolve, reject) => {
			try {
				console.log('创建@信息', options)
				const message = this.TUICore.createTextAtMessage(options);
				// 优化写法
				const messageList = [...this.store.messageList, message];
				// console.log("__________________________________________________________________________", JSON.stringify(message))
				store.commit("timStore/setMessageList", messageList);
				// var sendMessageAt = message.payload.text.replace('<span id='+'\'\'\'style=color:#2979ff\'>',)
				var sendMessageId = message.payload.text.replace(/'.*?'/g,'')
				var sendMessageSpan = sendMessageId.replace(/<span id= style=>/g,'')
				var sendMessageSpanNew = sendMessageSpan.replace(/<\/span>/g,'')
				const imResponse = await this.TUICore.sendMessage(message, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						description:sendMessageSpanNew,
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				this.store.messageList = this.store.messageList.map((item: any) => {
					if (item.ID === imResponse.data.message.ID) {
						return imResponse.data.message;
					}
					return item;
				});

				//保存到本地
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([message], false);
				}

				resolve(imResponse);
			} catch (error) {
				reject(error);
				const middleData = this.store.messageList;
				store.commit("timStore/resetChat");
				store.commit("timStore/setMessageList", middleData);
			}
		});
	}

	/**
	 * 发送表情消息
	 *
	 * @param {Object} data 消息内容
	 * @param {Number} data.index 表情索引
	 * @param {String} data.data 额外数据
	 * @returns {Promise}
	 */
	public sendFaceMessage(data: any): Promise<any> {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const options = this.handleMessageOptions(data, "face");
				const message = this.TUICore.createFaceMessage(options);
				// this.store.messageList.push(message);
				// 优化写法
				const messageList = [...this.store.messageList, message];
				store.commit("timStore/setMessageList", messageList);
				const imResponse = await this.TUICore.sendMessage(message, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				this.store.messageList = this.store.messageList.map((item: any) => {
					if (item.ID === imResponse.data.message.ID) {
						return imResponse.data.message;
					}
					return item;
				});

				//保存到本地
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([message], false);
				}

				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 发送图片消息
	 *
	 * @param {res} res 图片文件
	 * @param {image} 图片尺寸
	 * @returns {Promise}
	 */
	public sendImageMessage(res: any, image: any): Promise<any> {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const options = this.handleMessageOptions({ file: res }, "file");
				const message = this.TUICore.createImageMessage(options);
				// todo  上屏图片消息在发送之前没有尺寸，本地获取补充
				message.payload.imageInfoArray[1].height = image.height;
				message.payload.imageInfoArray[1].width = image.width;
				const messageList = [...this.store.messageList, message];
				store.commit("timStore/setMessageList", messageList);
				const imResponse = await this.TUICore.sendMessage(message, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				console.log('这里是++++++++++++++++++++++++++++++++++++++++++' + JSON.stringify(imResponse))
				this.store.messageList = this.store.messageList.map((item: any) => {
					if (item.ID === imResponse.data.message.ID) {
						return imResponse.data.message;
					}
					return item;
				});

				//保存到本地
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([message], false);
				}

				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 发送视频消息
	 *
	 * @param {Video} video 图片文件
	 * @returns {Promise}
	 */
	public sendVideoMessage(res: any, video: any): Promise<any> {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const options = this.handleMessageOptions({ file: res }, "file");
				console.log('111111111111111111111111111111111111111111' + JSON.stringify(options))
				const message = this.TUICore.createVideoMessage(options);
				// todo  上屏图片消息在发送之前没有尺寸，本地获取补充
				// message.payload.imageInfoArray[1].height = video.height
				// message.payload.imageInfoArray[1].width = video.width
				const messageList = [...this.store.messageList, message];
				store.commit("timStore/setMessageList", messageList);
				const imResponse = await this.TUICore.sendMessage(message, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				this.store.messageList = this.store.messageList.map((item: any) => {
					if (item.ID === imResponse.data.message.ID) {
						return imResponse.data.message;
					}
					return item;
				});

				//保存到本地
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([message], false);
				}

				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 发送语音消息
	 *
	 * @param {audio} audio 音频文件
	 * @returns {Promise}
	 */
	public sendAudioMessage(audio: any): Promise<any> {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const options = this.handleMessageOptions(
					{ file: audio },
					"file",
					(progress: number) => {
						this.handleUploadProgress(progress, message);
					}
				);
				console.log('发送语音的格式。。。。。。。。。。。。。。' + JSON.stringify(options))
				const message = this.TUICore.createAudioMessage(options);
				// todo  上屏图片消息在发送之前没有尺寸，待优化
				const messageList = [...this.store.messageList, message];
				store.commit("timStore/setMessageList", messageList);
				const imResponse = await this.TUICore.sendMessage(message, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				console.log("发送音频消息完成", imResponse);
				this.store.messageList = this.store.messageList.map((item: any) => {
					if (item.ID === imResponse.data.message.ID) {
						return imResponse.data.message;
					}
					return item;
				});

				//保存到本地
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([message], false);
				}

				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 发送文件消息
	 *
	 * @param {File} file 文件
	 * @returns {Promise}
	 */
	public sendFileMessage(message: any) {
		const messageList = [...this.store.messageList, message];
		store.commit("timStore/setMessageList", messageList);
		const imResponse = this.TUICore.sendMessage(message, {
			offlinePushInfo: {
				disablePush: false,
				androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
				extension: JSON.stringify({
					entity: { // entity 中的内容可自定义
						nick: message.nick,
						userID: message.conversationType == "GROUP" ? message.to : message.from,
						msgType: message.conversationType
					}
				})
			}
		});
		imResponse.then(function(imResponse) {

			this.saveLocalCacheMessageList([message], false);

			// 发送成功
			console.log("发送文件消息完成", imResponse);
			this.store.messageList = this.store.messageList.map((item: any) => {
				if (item.ID === imResponse.data.message.ID) {
					return imResponse.data.message;
				}
				return item;
			});
		}).catch(function(imError) {
			// 发送失败
			console.warn('sendMessage error:', imError);
		});


	}

	/**
	 * 发送自定义消息
	 *
	 * @param {Object} data 消息内容
	 * @param {String} data.data 自定义消息的数据字段
	 * @param {String} data.description 自定义消息的说明字段
	 * @param {String} data.extension 自定义消息的扩展字段
	 * @returns {Promise}
	 */
	public sendCustomMessage(data: any): Promise<any> {
		return this.handlePromiseCallback(async (resolve: any, reject: any) => {
			try {
				const options = this.handleMessageOptions(data, "custom");
				const message = this.TUICore.createCustomMessage(options);
				this.currentStore.messageList.push(message);
				const imResponse = await this.TUICore.sendMessage(message, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				console.log("发送自定义消息完成", imResponse);
				this.store.messageList = this.store.messageList.map((item: any) => {
					if (item.ID === imResponse.data.message.ID) {
						return imResponse.data.message;
					}
					return item;
				});

				//保存到本地
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([message], false);
				}

				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 发送地理位置消息
	 *
	 * @param {Object} data 消息内容
	 * @param {String} data.description 地理位置描述信息
	 * @param {Number} data.longitude 经度
	 * @param {Number} data.latitude 纬度
	 * @returns {Promise}
	 */
	public sendLocationMessage(data: any): Promise<any> {
		return this.handlePromiseCallback(async (resolve: any, reject: any) => {
			try {
				const options = this.handleMessageOptions(data, "location");
				const message = this.TUICore.createLocationMessage(options);
				this.store.messageList.push(message);
				const imResponse = await this.TUICore.sendMessage(message, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				console.log("发送地理位置消息完成", imResponse);

				//保存到本地
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([message], false);
				}

				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 转发消息
	 *
	 * @param {message} message 消息实例
	 * @param {any} to 转发的对象
	 * @returns {Promise}
	 */
	public forwardMessage(message: any, to: any): Promise<any> {
		return new Promise<void>(async (resolve, reject) => {
			try {
				let messageList
				let imMessage
				console.log('11111111111111111111111111', JSON.stringify(message))
				const options = this.handleMessageOptions(message, "forward", {}, to.to);
				// 转发文字
				if (message.type === 'TIMTextElem') {
					const text = message.payload.text
					const opt = {
						to: to.to,
						conversationType: to.conversationType,
						payload: {
							text: options.payload.payload.text
						}
					};
					imMessage = this.TUICore.createTextMessage(opt);
					if (message.conversationID === 'C2C' + to.to || message.conversationID === 'GROUP' + to.to) {
						messageList = [...this.store.messageList, imMessage];
						store.commit("timStore/setMessageList", messageList);
					}
					const imResponse = await this.TUICore.sendMessage(imMessage, {
						offlinePushInfo: {
							disablePush: false,
							androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
							extension: JSON.stringify({
								entity: { // entity 中的内容可自定义
									nick: message.nick,
									userID: message.conversationType == "GROUP" ? message.to : message.from,
									msgType: message.conversationType
								}
							})
						}
					});
					this.store.messageList = this.store.messageList.map((item: any) => {
						if (item.ID === imResponse.data.message.ID) {
							return imResponse.data.message;
						}
						return item;
					});

					//保存到本地
					if (imResponse.code == 0) {
						this.saveLocalCacheMessageList([imMessage], false);
					}

					resolve(imResponse);
				} else if (message.type === 'TIMImageElem') {
					const opt = {
						to: to.to,
						conversationType: to.conversationType,
						payload: {
							file: {
								tempFilePaths: [this.store.commonpath],
								tempFiles: [{
									path: this.store.commonpath,
									size: message.payload.imageInfoArray[0].size
								}]
							}
						},
						needReadReceipt: true
					}
					imMessage = this.TUICore.createImageMessage(opt);
					if (message.conversationID === 'C2C' + to.to || message.conversationID === 'GROUP' + to.to) {
						messageList = [...this.store.messageList, imMessage];
						store.commit("timStore/setMessageList", messageList);
					}
					imMessage.payload.imageInfoArray[0].width = message.payload.imageInfoArray[0].width
					imMessage.payload.imageInfoArray[0].height = message.payload.imageInfoArray[0].height
					const imResponse1 = await this.TUICore.sendMessage(imMessage, {
						offlinePushInfo: {
							disablePush: false,
							androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
							extension: JSON.stringify({
								entity: { // entity 中的内容可自定义
									nick: message.nick,
									userID: message.conversationType == "GROUP" ? message.to : message.from,
									msgType: message.conversationType
								}
							})
						}
					});
					this.store.messageList = this.store.messageList.map((item: any) => {
						if (item.ID === imResponse1.data.message.ID) {
							return imResponse1.data.message;
						}
						return item;
					});

					//保存到本地
					if (imResponse1.code && imResponse1.code == 0) {
						this.saveLocalCacheMessageList([imMessage], false);
					}
				} else if (message.type === 'TIMVideoFileElem') {
					const opt = {
						to: to.to,
						conversationType: to.conversationType,
						payload: {
							file: {
								tempFilePath: this.store.commonpath,
								size: message.payload.videoSize,
								with: message.payload.thumbWidth,
								height: message.payload.thumbHeight,
							},
						}
					}
					imMessage = await this.TUICore.createVideoMessage(opt);
					if (message.conversationID === 'C2C' + to.to || message.conversationID === 'GROUP' + to.to) {
						messageList = [...this.store.messageList, imMessage];
						store.commit("timStore/setMessageList", messageList);
					}
					const imResponse = await this.TUICore.sendMessage(imMessage, {
						offlinePushInfo: {
							disablePush: false,
							androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
							extension: JSON.stringify({
								entity: { // entity 中的内容可自定义
									nick: message.nick,
									userID: message.conversationType == "GROUP" ? message.to : message.from,
									msgType: message.conversationType
								}
							})
						}
					});
					this.store.messageList = this.store.messageList.map((item: any) => {
						if (item.ID === imResponse.data.message.ID) {
							return imResponse.data.message;
						}
						return item;
					});

					//保存到本地
					if (imResponse.code == 0) {
						this.saveLocalCacheMessageList([imMessage], false);
					}
					store.commit("timStore/setCommonpath", '')
				} else if (message.type === 'TIMFileElem') {
					const msg = {
						files: [
							{
								name: message.payload.fileName, // 文件名
								size: message.payload.fileSize, //本地文件大小
								path: this.store.commonpath, //本地文件路径
								lastModified: 0, // 修改时间
							},
						]
					}
					const opt = {
						to: to.to,
						conversationType: to.conversationType,
						payload: {
							file: msg
						}
					}
					imMessage = await this.TUICore.createFileMessage(opt);
					if (message.conversationID === 'C2C' + to.to || message.conversationID === 'GROUP' + to.to) {
						messageList = [...this.store.messageList, imMessage];
						store.commit("timStore/setMessageList", messageList);
					}
					const imResponse = await this.TUICore.sendMessage(imMessage, {
						offlinePushInfo: {
							disablePush: false,
							androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
							extension: JSON.stringify({
								entity: { // entity 中的内容可自定义
									nick: message.nick,
									userID: message.conversationType == "GROUP" ? message.to : message.from,
									msgType: message.conversationType
								}
							})
						}
					});
					this.store.messageList = this.store.messageList.map((item: any) => {
						if (item.ID === imResponse.data.message.ID) {
							return imResponse.data.message;
						}
						return item;
					});

					//保存到本地
					if (imResponse.code == 0) {
						this.saveLocalCacheMessageList([imMessage], false);
					}
					store.commit("timStore/setCommonpath", '')
				}else if (message.type === 'TIMSoundElem'){
					console.log('dddddddddddddddddddddddddddddddddd',JSON.stringify(message))
					const opt = {
						to: to.to,
						conversationType: to.conversationType,
						payload: {
							file: {
								tempFilePath: this.store.commonpath,
								fileSize: message.payload.size,
								duration:message.payload.second*1000,
							},
						}
					}
					imMessage = await this.TUICore.createAudioMessage(opt);
					console.log('cescecscececeeccee',JSON.stringify(imMessage))
					if (message.conversationID === 'C2C' + to.to || message.conversationID === 'GROUP' + to.to) {
						messageList = [...this.store.messageList, imMessage];
						store.commit("timStore/setMessageList", messageList);
					}
					const imResponse = await this.TUICore.sendMessage(imMessage, {
						offlinePushInfo: {
							disablePush: false,
							androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
							extension: JSON.stringify({
								entity: { // entity 中的内容可自定义
									nick: message.nick,
									userID: message.conversationType == "GROUP" ? message.to : message.from,
									msgType: message.conversationType
								}
							})
						}
					});
					this.store.messageList = this.store.messageList.map((item: any) => {
						if (item.ID === imResponse.data.message.ID) {
							return imResponse.data.message;
						}
						return item;
					});

					//保存到本地
					if (imResponse.code == 0) {
						this.saveLocalCacheMessageList([imMessage], false);
					}
					store.commit("timStore/setCommonpath", '')
				}
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 转发消息
	 * createForwardMessage 调用接口报错啥的都不返回
	 *
	 * @param {message} message 消息实例
	 * @param {any} to 转发的对象
	 * @returns {Promise}
	 */
	public forwardMessage2(message: any, to: any): Promise<any> {
		console.log("进来拉。。。。。111111111111")
		return new Promise<void>(async (resolve, reject) => {
			try {
				console.log("进来拉。。。。。22222")
				const options = this.handleMessageOptions(message, "forward", {}, to);
				console.log("to", to);
				const message2 = this.TUICore.createForwardMessage(options);
				console.log("imMessage", imMessage);
				const imResponse = await this.TUICore.sendMessage(imMessage, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				console.log("消息转发完成", imResponse);
				// if (
				// 	this.store.conversation.conversationID ===
				// 	imResponse.data.message.conversationID
				// ) {
				// 	this.store.messageList.push(imResponse.data.message);
				// }

				//保存到本地
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([imMessage], false);
				}
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 发送@ 提醒功能的文本消息
	 *
	 * @param {Object} data 消息内容
	 * @param {String} data.text 文本消息
	 * @param {Array} data.atUserList 需要 @ 的用户列表，如果需要 @ALL，请传入 TIM.TYPES.MSG_AT_ALL
	 * @returns {message}
	 *
	 * - 注：此接口仅用于群聊
	 */
	public sendTextAtMessage(data: Object) {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const options = this.handleMessageOptions(data, "text");
				const message = this.TUICore.createTextAtMessage(options);
				this.currentStore.messageList.push(message);
				const imResponse = await this.TUICore.sendMessage(message, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				this.currentStore.messageList = this.currentStore.messageList.map(
					(item: any) => {
						if (item.ID === imResponse.data.message.ID) {
							return imResponse.data.message;
						}
						return item;
					}
				);

				//保存到本地
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([message], false);
				}

				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 发送合并消息
	 *
	 * @param {Object} data 消息内容
	 * @param {Array.<Message>} data.messageList 合并的消息列表
	 * @param {String} data.title 合并的标题
	 * @param {String} data.abstractList 摘要列表，不同的消息类型可以设置不同的摘要信息
	 * @param {String} data.compatibleText 兼容文本
	 * @returns {Promise}
	 */
	public sendMergerMessage(data: any): Promise<any> {
		return new Promise<void>(async (resolve: any, reject: any) => {
			try {
				console.log('合并消息内容是什么+++++++++++++++++++++++++++++++', JSON.stringify(data))
				const options = this.handleMessageOptions1(data, "merger");
				const message = this.TUICore.createMergerMessage(options);
				if (data.messageList[0].conversationID === 'C2C' + data.to || data.messageList[0].conversationID === 'GROUP' + data.to) {
					const messageList = [...this.store.messageList, message];
					store.commit("timStore/setMessageList", messageList);
				}
				const imResponse = await this.TUICore.sendMessage(message, {
					offlinePushInfo: {
						disablePush: false,
						androidOPPOChannelID: '123456',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
						extension: JSON.stringify({
							entity: { // entity 中的内容可自定义
								nick: message.nick,
								userID: message.conversationType == "GROUP" ? message.to : message.from,
								msgType: message.conversationType
							}
						})
					}
				});
				this.store.messageList = this.store.messageList.map((item: any) => {
					if (item.ID === imResponse.data.message.ID) {
						return imResponse.data.message;
					}
					return item;
				});

				//保存到本地
				if (imResponse.code == 0) {
					this.saveLocalCacheMessageList([message], false);
				}
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}
	public async getLocalCacheMessageList(options: any, history?: Boolean) {

		// console.log("进来了。。。。。。。", this.currentStore.isCompleted)
		if (this.currentStore.isCompleted) {
			return
		}

		let messageList = [];

		let data = await this.getStorageMsg(options);
		// console.log("data", data)
		if (data.length) {

			//检查是否有新的腾讯云消息拉
			let timMessageList = [];
			options.count = 50;
			options.direction = 1;
			options.sequence = data[data.length - 1].sequence;
			options.time = data[data.length - 1].time;
			// console.log('111111111111111111')
			
			//获取当前网络状况
			let networkType = null;
			await uni.getNetworkType({
				success: function(res) {
					networkType = res.networkType
				},
			});
			
			if (networkType != 'none') {
				// console.log("options", options);
				let imResponse = await this.TUICore.getMessageListHopping(options);
				// console.log("imResponse", imResponse);
				timMessageList = imResponse.data.messageList || [];
				if (timMessageList.length) {
				
					//检查腾讯云消息是否最新的
					if(this.store.messageList!=''){
						var oldMessageTime = this.store.messageList[this.store.messageList.length-1].time;
					}else{
						var oldMessageTime = data[data.length - 1].time;
					}
						              
					// let oldMessageTime = this.store.messageList[this.store.messageList.length-1].time;
					timMessageList = timMessageList.filter(item => item.time > oldMessageTime)
					// console.log("oldMessageTime", JSON.stringify(oldMessageTime))
					// console.log("timMessageList", JSON.stringify(timMessageList))
					if (timMessageList.length) {
						this.saveLocalCacheMessageList(timMessageList, false);
						data = [
							...data,
							...timMessageList,
						]
					}
				}
			}
			
			
			// if (imResponse.data.isCompleted) {
			// 	this.currentStore.isCompleted = true;
			// } else {
			// 	this.currentStore.isCompleted = false;
			// }
			if (!history) {
				messageList = data;
			} else {
				messageList = [
					...data,
					...this.store.messageList,
				];
			}

		} else {

			// console.log("获取腾讯云的数据拉。。。。。。。。。。。。。")
			
			let timMessageList = [];

			//获取腾讯云接口数据
			let isCompleted = uni.getStorageSync(options.conversationID + '-tim-isCompleted') || false;
			// console.log("isCompleted", isCompleted)
			if (!isCompleted) {

				try {

					// console.log("options", options)
					
					//获取当前网络状况
					let networkType = null;
					await uni.getNetworkType({
						success: function(res) {
							networkType = res.networkType
						},
					});
					
					if (networkType != 'none') {
						let imResponse = await this.TUICore.getMessageList(options);
						// console.log("imResponse", imResponse);
						timMessageList = imResponse.data.messageList || [];
						if (timMessageList.length) {
							if (!history) {
								messageList = timMessageList;
							} else {
								messageList = [
									...timMessageList,
									...this.store.messageList,
								];
							}
						
							//保存聊天信息到本地
							// console.log("进来保存了。。。。。。。")
							this.saveLocalCacheMessageList(timMessageList);
							// console.log("进来保存了222222222222")
						
							//补充下条消息 ID
							if (imResponse.data.nextReqMessageID) {
								this.currentStore.nextReqMessageID = imResponse.data.nextReqMessageID;
							}
						}
						
						//检查腾讯云消息接口是否拉取完了
						if (imResponse.data.isCompleted) {
							isCompleted = true;
							this.currentStore.isCompleted = true;
							uni.setStorageSync(options.conversationID + '-tim-isCompleted', true)
						} else {
							this.currentStore.isCompleted = false;
						}
					}
					
					
				} catch (error) {
					console.log("error", error)
				}
			}

			//如果腾讯云接口拉完历史消息，则拉取 iDOCK
			if (timMessageList.length == 0) {

				//获取最新消息时间
				let lastMessageTime = 0;
				if (this.store.messageList.length > 0) {
					lastMessageTime = this.store.messageList[0].time;
				} else if (messageList.length > 0) {
					lastMessageTime = messageList[0].time;
				}

				// console.log("lastMessageTime", lastMessageTime)

				await httpInterceptor.get('/mgr/tim/chat/conversation/history/message', { conversation_id: options.conversationID, last_message_time: lastMessageTime }).then(res => {
					console.log("res", res);
					if (res.length == 0) {
						this.currentStore.isCompleted = true;
					} else {
						this.currentStore.isCompleted = false;
						// console.log('111111111111111111111111111111111111111',JSON.stringify(res))
						//保存聊天信息到本地
						this.saveLocalCacheMessageList(res);
					}

					if (!history && messageList.length == 0) {
						
						messageList = res
					} else {

						if (messageList.length == 0) {
							
							messageList = this.store.messageList
						}
						messageList = [
							...res,
							...messageList,
						];
					}
				})
			}

		}

		// console.log("设置了messageList", messageList);
		if (messageList.length > 0) {
			store.commit("timStore/setMessageList", messageList);
		}
	}

	public async getStorageMsg(param = {}) {
		// console.log("param", param)
		let res = await timStorage.getData({
			conversation_id: param.conversationID,
			page: param.page || 0,
			sequence: param.lastMessageTime,
			isBefore: true,
		});
		// console.log("getStorageMsg", res);
		return res;
	}

	public async saveLocalCacheMessageList(data, isBefore = true) {
		// console.log("保存历史消息拉", data);
		// console.log("isBefore", isBefore);
		// console.log("this.store.conversationID", this.store.conversationID);
		timStorage.insert([...data], isBefore, this.store.conversationID)
	}

	/**
	 * 获取 messageList
	 *
	 * @param {any} options 获取 messageList 参数
	 * @param {Boolean} history  是否获取历史消息
	 * @returns {Promise}
	 */
	public async getMessageList(options: any, history?: Boolean) {
		return new Promise<void>(async (resolve, reject) => {
			try {
				let imResponse = {}
				let messageList = [];
				let lastMessageTime = 0;
				if (!this.currentStore.isServer) {
					imResponse = await this.TUICore.getMessageList(options);
					if (!history) {
						messageList = imResponse.data.messageList;
					} else {
						messageList = [
							...imResponse.data.messageList,
							...this.store.messageList,
						];
					}
					this.currentStore.nextReqMessageID = imResponse.data.nextReqMessageID;

					//检查腾讯云消息接口是否拉取完了
					if (imResponse.data.isCompleted) {
						this.currentStore.isServer = true;
					}
				}

				//获取最新消息时间
				if (this.store.messageList.length > 0) {
					lastMessageTime = this.store.messageList[0].time;
				}
				
				//如果腾讯云接口拉完历史消息，则拉取 iDOCK
				if (this.currentStore.isServer) {
					await httpInterceptor.get('/mgr/tim/chat/conversation/history/message', {
						conversation_id: options.conversationID,
						last_message_time: lastMessageTime
					}).then(res => {
						console.log("返回的消息列表-------------", res.length);
						if (res.length == 0) {
							this.currentStore.isCompleted = true;
						} else {
							this.currentStore.isCompleted = false;
						}
						if (!history && messageList.length == 0) {
							messageList = res
						} else {

							if (messageList.length == 0) {
								messageList = this.store.messageList
							}
							messageList = [
								...res,
								...messageList,
							];
						}
					})
				} else {
					this.currentStore.isCompleted = false;
				}
				store.commit("timStore/setMessageList", messageList);
				console.log(imResponse)
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 获取历史消息
	 *
	 * @returns {Promise}
	 */
	public async getHistoryMessageList() {
		return new Promise<void>(async (resolve, reject) => {
			try {
				console.log("获取历史呀。。。。。", this.currentStore.isCompleted)
				if (!this.currentStore.isCompleted) {

					let lastMessageTime = 0;
					if (this.store.messageList.length > 0) {
						lastMessageTime = this.store.messageList[0].time;
					}

					let nextReqMessageID = this.currentStore.nextReqMessageID || "";
					if (nextReqMessageID == "") {
						nextReqMessageID = this.store.messageList[0].sequence - 1;
					}

					this.getLocalCacheMessageList({
						conversationID: this.store.conversation.conversationID,
						lastMessageTime: lastMessageTime,
						nextReqMessageID: nextReqMessageID.toString(),
						count: 15,
					}, true);
					// messageList = await this.getMessageList(options, true);
				}
				resolve();
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 消息撤回
	 *
	 * @param {message} message 消息实例
	 * @returns {Promise}
	 */
	public revokeMessage(message: any): Promise<any> {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const imResponse = await this.TUICore.revokeMessage(message);
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 重发消息
	 *
	 * @param {message} message 消息实例
	 * @returns {Promise}
	 */
	public resendMessage(message: any): Promise<any> {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const imResponse = await this.TUICore.resendMessage(message);
				console.log("消息重发完成", imResponse);
				let messageList = [];
				messageList = this.store.messageList.filter(
					(item: any) => item.ID !== message.ID
				);
				store.commit("timStore/setMessageList", messageList);
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 删除消息
	 *
	 * @param {Array.<message>} messages 消息实例
	 * @returns {Promise}
	 */
	public deleteMessage(messages: any): Promise<any> {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const imResponse = await this.TUICore.deleteMessage(messages);
				let messageList = [];
				messageList = this.store.messageList.filter(
					(item: any) => item.ID !== messages.ID
				);
				store.commit("timStore/setMessageList", messageList);
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}
}
